<template>
	<section>
		<!--工具条--><!--高级查询-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" :model="filters">
				<el-form-item>
					<el-input v-model="filters.keyword" placeholder="关键字"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" v-on:click="search">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd">新增</el-button>
				</el-form-item>
			</el-form>
		</el-col>

		<!--列表--><!--列表-->
    <el-table :data="employees" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column type="index" width="60">
      </el-table-column>
      <el-table-column prop="username" label="员工姓名" width="120" >
      </el-table-column>
      <el-table-column prop="phone" label="电话" width="100" >
      </el-table-column>
      <el-table-column prop="email" label="邮箱" width="100" >
      </el-table-column>
      <el-table-column prop="password" label="密码" width="100" >
      </el-table-column>
      <el-table-column prop="age" label="年龄" width="100" >
      </el-table-column>
      <el-table-column prop="state" label="状态" width="100" :formatter="formatSex" sortable>
        <template scope="scope">
          <span v-if="scope.row.state == 1" style="color: green">启用</span>
          <span v-else-if="scope.row.state == 0" style="color: red">禁用</span>
          <span v-else style="color: gray">未知</span>
        </template>
      </el-table-column>
      <el-table-column prop="department.name" label="部门" width="120" >
      </el-table-column>
      <el-table-column prop="shop.name" label="店铺" width="120" >
      </el-table-column>
      <el-table-column label="操作" width="150">
        <template scope="scope">
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

		<!--工具条--><!--底层批量删除-->
		<el-col :span="24" class="toolbar">
			<el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
			<el-pagination layout="prev, pager, next" @current-change="handleCurrentChange"
                     :page-size="pageSize"
                     :current-page="currentPage"
                     :total="total"
                     style="float:right;">
			</el-pagination>
		</el-col>



		<!--编辑界面--><!--编辑页面-->
		<el-dialog :title="title" :visible.sync="editFormVisible" :close-on-click-modal="false">
			<el-form :model="editForm" label-width="80px" :rules="editFormRules" ref="editForm">
        <el-form-item label="员工姓名" prop="username">
          <el-input v-model="editForm.username" auto-complete="off"></el-input>
        </el-form-item>
				<el-form-item label="手机号" prop="phone">
					<el-input v-model="editForm.phone" auto-complete="off"></el-input>
				</el-form-item>
        <el-form-item label="邮  箱" prop="email">
          <el-input v-model="editForm.email" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="密  码" prop="password">
          <el-input v-model="editForm.password" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="年  龄" prop="age">
          <el-input v-model="editForm.age" auto-complete="off"></el-input>
        </el-form-item>
				<el-form-item label="启用状态">
					<el-radio-group v-model="editForm.state">
						<el-radio class="radio" :label="1">启用</el-radio>
						<el-radio class="radio" :label="0">禁用</el-radio>
					</el-radio-group>
				</el-form-item>
        <el-form-item label="部门名称">
          <el-select v-model="editForm.departmentId" placeholder="请选择">
            <el-option
                v-for="item in department"
                :label="item.name"
                :value="item.id">
              <span style="float: left">{{ item.name }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.sn }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="店铺名称">
          <el-select v-model="editForm.shopId" placeholder="请选择">
            <el-option
                v-for="item in shop"
                :label="item.name"
                :value="item.id">
              <span style="float: left">{{ item.name }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.tel }}</span>
            </el-option>
          </el-select>
        </el-form-item>
<!--        <el-form-item label="上级部门">-->
<!--          <div class="block">-->
<!--            <el-cascader-->
<!--                v-model="editForm.parentId"-->
<!--                :options="options"-->
<!--                :props="{ /*checkStrictly: true*/expandTrigger: 'hover',-->
<!--                  value:'id',-->
<!--                  label:'name'-->
<!--                  }"-->
<!--                @change="handleChange">-->
<!--                </el-cascader>-->
<!--          </div>-->
<!--        </el-form-item>-->
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="editFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="editSubmit" :loading="editLoading">提交</el-button>
			</div>
		</el-dialog>

		<!--新增界面--><!--新增页面-->
	</section>
</template>

<script>
	import util from '../../common/js/util'
	//import NProgress from 'nprogress'
	import { getEmployeeListPage, removeEmployee, batchRemoveEmployee, editEmployee, addEmployee } from '../../api/api';

	export default {
		data() {
			return {
        options: [],
        title:'',
        employees: [],
				filters: {
					keyword: ''
				},
        department: [],
        shop:[],
				total: 0,
        pageSize:5,
        currentPage:1,
				listLoading: false,
				sels: [],//列表选中列

				editFormVisible: false,//编辑界面是否显示
				editLoading: false,
				editFormRules: {
          username: [
            { required: true, message: '请输入员工姓名', trigger: 'blur' }
          ],
          phone: [
						{ required: true, message: '请输入手机号', trigger: 'blur' }
					]
				},
				//编辑界面数据
				editForm: {
          id: null,
          username: '',
          phone: '',
          email: '',
          password: '',
          age: '',
          state: 1,
          departmentId: null,
          shopId: null
				},

				addFormVisible: false,//新增界面是否显示
				addLoading: false,
				addFormRules: {
					name: [
						{ required: true, message: '请输入姓名', trigger: 'blur' }
					]
				},
				//新增界面数据
				// addForm: {
				// 	name: '',
				// 	sex: -1,
				// 	age: 0,
				// 	birth: '',
				// 	addr: ''
				// }
			}
		},
		methods: {
			//性别显示转换
			formatSex: function (row, column) {
				return row.sex == 1 ? '男' : row.sex == 0 ? '女' : '未知';
			},
			handleCurrentChange(val) {
				this.currentPage = val;
				this.getEmployees();
			},
      //高级查询函数
      search(){
			  //设置页码为第1页
			  this.currentPage = 1,
        //获取部门列表方法
        this.getEmployees()
      },
			//获取部门列表
			getEmployees() {
				let para = {
				  currentPage:this.currentPage,
          pageSize:this.pageSize,
          keyword: this.filters.keyword
				};
				//开启列表加载忙等框
				this.listLoading = true;
        this.$http.post("/emp",para)
        .then(result=>{
            this.listLoading = false;
            this.total = result.data.totals;
            this.employees = result.data.rows;
        })
			},
			//删除
			handleDel: function (index, row) {
				this.$confirm('确认删除该记录吗?', '提示', {
					type: 'warning'
				}).then(() => {
          this.listLoading = true;
          this.$http.delete("/emp/"+row.id)
          .then(result=>{
            this.listLoading = false;
            if (result.data.success){
              //删除成功
              this.currentPage = 1;
              this.getEmployees()
            }else{
              //删除失败
              this.$message({
                message: result.data.msg,
                type: 'warning'
              });
            }
          })
          .catch(result=>{
            this.$message({
              message: "网络异常，开摆吧！",
              type: 'warning'
            });
          })
				})
			},
			//显示编辑界面
			handleEdit: function (index, row) {
        this.title = "修改信息";
				this.editFormVisible = true;
				this.editForm = Object.assign({}, row);
        console.log(this.editForm.departmentId)
			},
			//显示新增界面
			handleAdd: function () {
        this.title = "添加员工";
				this.editFormVisible = true;
				this.editForm = {
          id: null,
          username: '',
          phone: '',
          email: '',
          password: '',
          age: '',
          state: 1,
          departmentId: null,
          shopId: null
				};
			},
			//编辑和添加
			editSubmit: function () {
				this.$refs.editForm.validate((valid) => {
					if (valid) {
						this.$confirm('确认提交吗？', '提示', {}).then(() => {
							this.editLoading = true;
							let para = Object.assign({}, this.editForm);
							//上级部门框数据转化
              //无穷级数（级数编号数组）
              // if (para.parentId && para.parentId instanceof Array){ // para.parentId 是个 []
              //   let array = para.parentId;
              //   console.log(para.parentId)
              //   console.log(array[array.length - 1])
              //   para.parentId = array[array.length - 1];
              // }
							this.$http.put("/emp",para)
              .then(result=>{
                this.editFormVisible = false; // 编辑界面是否显示
                this.editLoading = false; // 编辑界面加载
                if (result.data.success){
                  this.currentPage = 1;
                  this.getEmployees();
                }else{
                  this.$message({
                    message: result.data.msg,
                    type: 'warning'
                  });
                }
              })
						});
					}
				});
			},
			//新增
      //勾选批量选择按钮获取行数据
			selsChange: function (sels) {
			  console.log(sels)
				this.sels = sels;
			},
			//批量删除
			batchRemove: function () {
			  //将行数据中的id取出 生成一个新集合
				var ids = this.sels.map(item => item.id);
				this.$confirm('确认删除选中记录吗？', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true;
          this.$http.patch("/emp",ids)
          .then(result=>{
              this.listLoading = false;
              if (result.data.success) {
                //删除成功
                this.currentPage = 1;
                this.getEmployees()
            }else{
              this.$message({
                message: result.data.msg,
                type: 'warning'
              });
            }
          })
          .catch(result=>{
            this.$message({
              message: "网络异常，开摆吧！",
              type: 'warning'
            });
          })
				}).catch(() => {

				});
			},
      // 获取部门列表
      getDepartment(){
        this.$http.get("/dept")
            .then(result=>{
              this.department = result.data

            })
            .catch(result=>{

            })
      },
      //获取店铺列表
      getShop(){
        this.$http.get("/shop")
            .then(result=>{
              this.shop = result.data
            })
            .catch(result=>{

            })
      },
      //无限级数后端获取
      getDeptTree(){
			  this.$http.get("/dept/tree")
        .then(result=>{
          this.options = result.data
        })
        .catch(result=>{

        })
      },
      handleChange(value) {
        console.log(value);
      }
		},
		mounted() {
			this.getEmployees();
			this.getDepartment();
      this.getShop();
			this.getDeptTree();
		}
	}

</script>

<style scoped>

</style>